<?php
namespace app\admin\model;
/**
 * @Author: user
 * @Date:   2019-04-02 15:18:36
 * @Last Modified by:   user
 * @Last Modified time: 2019-04-08 16:53:04
 */
use think\Model;
use think\Db;
use app\admin\model\AdminMenuModel;
/**
 * 模块菜单模型
 */
class ModuleMenuModel extends Model
{
	/**
	 * 新增
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public function saveMenu( $company , $menus , $moduleId , $isCustom = 0 )
	{
		$mainMenuId = -1;
		$find = $this->where( 'menu_id' , $menus['mainMenu']  )->where( 'company_id' , $company )->find();
		if( !$find ){
			$mainMenuId = $this->insertGetId( [ 'company_id' => $company , 'menu_id' => $menus['mainMenu'] , 'module_id' => $moduleId , 'custom' => $isCustom ]);
		}else{
			$mainMenuId = $find['id'];
		}
		foreach ( $menus['subMenu'] as $key => $value ) {

			$find = $this->where( 'menu_id' , $value  )->where( 'company_id' , $company )->find();

			if( !$find ){

				$this->insertGetId( [ 'company_id' => $company , 'menu_id' => $value , 'module_id' => $moduleId , 'custom' => $isCustom  ]);
			}
		}
		return $mainMenuId;
	}

	/**
	 * 删除
	 * @param  [type] $where [description]
	 * @return [type]        [description]
	 */
	public function deleteMenu($id)
	{
		return $this->where($id)->delete();
	}
	/**
	 * 增强版删除adminMenu中的菜单
	 * @param  $id 模块菜单id 需要通过模块菜单查找原始菜单 ，获取所有原始子级菜单id
	 * @param  $companyId 公司id
	 * @return [type]     [description]
	 */
	public function deleteMenuPlus($id,$companyId)
	{
		//根据模块菜单id 查找原始菜单 根据原始菜单和公司id删除菜单
		$ids = $this->getSubMenus( $id );
		$ids [] = $id ;
		//删除auth_access中的菜单数据 相应的授权菜单也要删除
		Db::name( 'auth_access' )->where( 'menu_id' , 'IN' , $ids )->where( 'company' , $companyId )->delete();
		//删除模块菜单  条件：原始菜单id 和 公司id 
		return Db::name('module_menu')->where( 'menu_id' , 'IN' , $ids )->where( 'company_id' , $companyId )->delete();
	}

	/**
	 * 通过主菜单获取子级菜单ids
	 */
	private function getSubMenus( $menuId , $menuids = [] )
	{
		$ids = Db::name( 'admin_menu' )->where( 'parent_id' , $menuId )->column( 'id' );
		if( $ids ){
			foreach ($ids as $key => $value) {
				$menuids [] = $value;
				$this->getSubMenus( $value , $menuids );
			}
		}
		return $menuids;
	}

}